<template>
  <div class="client-group">
    <div class="search-box">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-button type="primary" :icon="Plus" @click="handelNewGroup">新建</el-button>
        </el-col>
      </el-row>
    </div>
    <el-table
      v-loading="isLoading"
      element-loading-text="数据加载中..."
      :data="listData"
      stripe
      style="width: 100%"
      border
      :header-cell-style="{ background: '#F2F6FC', color: '#909399', 'font-weight': 400, 'font-size': '14px' }"
      :row-class-name="tableRowClassName"
    >
      <el-table-column prop="customerGroupName" label="分组名称" fixed="left" width="150" show-overflow-tooltip />
      <el-table-column prop="desc" label="描述" show-overflow-tooltip />
      <el-table-column prop="orderNum" label="排序" width="100" show-overflow-tooltip></el-table-column>
      <el-table-column prop="createTime" label="发布时间" width="200" show-overflow-tooltip></el-table-column>
      <el-table-column label="禁用启用" width="110">
        <template #default="{ row }">
          <el-switch v-model="row.status" :loading="row.statusLoading" @change="changeStatus(row)" />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button type="primary" link @click="handelEditGroup(row)">编辑</el-button>
          <el-button type="primary" link :loading="row.delLoading" @click="handelDeleteGroup(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <custom-pagination
      :total="listTotal"
      v-model:limit="pageParams.size"
      v-model:page="pageParams.current"
      layout="total, sizes, prev, pager, next, jumper"
      @pagination="handelPage"
    >
    </custom-pagination>

    <!--  添加/编辑分组 start  -->
    <div class="client-group-drawer">
      <el-drawer v-model="isOpenGroupDrawer" :size="861" destroy-on-close @close="handelGroupCancel">
        <template #header>
          <title-view :title="groupDrawerTitle" />
        </template>
        <template #default>
          <Condition ref="conditionRef" v-loading="isGroupLoading" v-if="isOpenGroupDrawer" v-model="formData" />
        </template>
        <template #footer>
          <div class="flex-center">
            <el-button style="width: 92px; background-color: #f2f3f5" @click="handelGroupCancel">取消</el-button>
            <el-button style="width: 92px" type="primary" @click="handelGroupConfirm">保存</el-button>
          </div>
        </template>
      </el-drawer>
    </div>
    <!--  添加/编辑分组 end  -->
  </div>
</template>

<script setup>
import { ref, getCurrentInstance } from "vue";
import { Plus } from "@element-plus/icons-vue";
import _ from "lodash";
import { tableRowClassName } from "./utils";
import usePageList from "@/hooks/usePageList";
import Condition from "./components/Condition";
import * as groupApi from "@/apis/clientGroup/clientGroup";
import useUserStore from "@/store/modules/user";

const { proxy } = getCurrentInstance();
const userStore = useUserStore();

const { isLoading, listData, listTotal, pageParams, getListData, handelPage } = usePageList(groupApi.clientGroupList);

const changeStatus = async row => {
  try {
    row.statusLoading = true;
    await groupApi.clientGroupStatus(row.customerGroupId, row.status);
    proxy.$modal.msgSuccess(row.status ? "启用成功" : "禁用成功");
    getListData();
    row.statusLoading = false;
  } catch (err) {
    row.status = !row.status;
    row.statusLoading = false;
  }
};

const isOpenGroupDrawer = ref(false);
const isGroupLoading = ref(false);
const groupDrawerTitle = ref("");
const formData = ref({
  customerGroupName: "",
  orderNum: 0,
  desc: "",
  status: true,
  tenantId: userStore.userInfo.tenantId,
  conditions: [
    // {
    //   groupType: "",
    //   conditions: [
    //     {
    //       title: "",
    //       fieldName: "",
    //       fieldId: "",
    //       fieldType: ,
    //       compare: "",
    //       value: []
    //     }
    //   ]
    // }
  ]
});

const handelNewGroup = () => {
  isOpenGroupDrawer.value = true;
  groupDrawerTitle.value = "添加分组";
};

const getGroupDetail = async row => {
  try {
    isGroupLoading.value = true;
    const { data } = await groupApi.clientGroupDetail(row.customerGroupId);
    formData.value = data || {};
    formData.value.conditions = JSON.parse(formData.value.condition);
    isGroupLoading.value = false;
  } catch (err) {
    isGroupLoading.value = false;
  }
};
const handelEditGroup = row => {
  isOpenGroupDrawer.value = true;
  groupDrawerTitle.value = "编辑分组";
  getGroupDetail(row);
};

const handelGroupCancel = () => {
  formData.value = {
    customerGroupName: "",
    orderNum: 0,
    desc: "",
    status: true,
    tenantId: userStore.userInfo.tenantId,
    conditions: []
  };
  isOpenGroupDrawer.value = false;
};
const handelGroupConfirm = async () => {
  const result = await proxy.$refs.conditionRef.submit();
  if (!result) {
    return proxy.$modal.msgError("请填写必填项");
  }
  try {
    const addEditApi = formData.value.customerGroupId ? groupApi.clientGroupEdit : groupApi.clientGroupAdd;
    const postData = _.cloneDeep(formData.value);
    postData.condition = JSON.stringify(postData.conditions);
    isGroupLoading.value = true;
    await addEditApi(postData);
    isGroupLoading.value = false;
    isOpenGroupDrawer.value = false;
    getListData();
    proxy.$modal.msgSuccess("操作成功");
  } catch (err) {
    isGroupLoading.value = false;
  }
};

const deleteGroupFun = row => {
  row.delLoading = true;
  groupApi
    .clientGroupDelete(row.customerGroupId)
    .then(() => {
      row.delLoading = false;
      proxy.$modal.msgSuccess("删除成功");
      getListData();
    })
    .catch(() => {
      row.delLoading = false;
    });
};
const handelDeleteGroup = row => {
  proxy.$modal
    .confirm("确认删除吗?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    })
    .then(() => {
      deleteGroupFun(row);
    })
    .catch(() => {});
};
</script>

<style scoped lang="scss">
@use "clientGroup";
</style>
